package cn.dlc.com.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.dlc.com.mapper.LockMapper;
import cn.dlc.com.mapper.LockRecord;
import tk.mybatis.mapper.entity.Example;

/**
 * 
 * Copyright: Copyright (c) 2020 
 * 
 * @Description: 实现锁
 *
 * @version: v1.0.0
 * @author: 立川
 * @date: 2020年8月25日 上午7:21:33
 */
@Component
public class DbLock implements Lock{
	
	@Autowired
	private LockMapper lockMapper;
	
	private final String LOCK_NAME = "lock_name";

	@Override
	public void lock() {
		// 首先尝试上锁，不行的话等待，
		while(true) {
			boolean tryLock = tryLock();
			if(tryLock) {
				// 之前没有锁的话上一把锁
				LockRecord lockRecord = new LockRecord();
				lockRecord.setLockName(LOCK_NAME);
				lockMapper.insert(lockRecord);
				return;
			} else {
				System.out.println("waiting....");
			}
		}
	}
	
	/**
	 * 尝试获取锁
	 */
	@Override
	public boolean tryLock() {
		// 创建查询对象
		Example example = new Example(LockRecord.class);
		example.createCriteria().andEqualTo("lockName", LOCK_NAME);
		// 直接找这条记录
		LockRecord result = lockMapper.selectOneByExample(example);
		if(result == null) {
			return true;
		}
		
		return false;
	}
	
	@Override
	public void unlock() {
		// 创建查询对象，
		Example example = new Example(LockRecord.class);
		example.createCriteria().andEqualTo("lockName", LOCK_NAME);
		// 删除这把锁
		lockMapper.deleteByExample(example);
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		
	}

	
	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		return false;
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
